'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('【createNotification】云函数被调用，event：', event);

  const { 
    userId, 
    type, 
    category, 
    title, 
    content, 
    relatedId, 
    relatedType, 
    priority = 'normal',
    actionUrl, 
    actionText 
  } = event;

  if (!userId || !title || !content) {
    return { 
      success: false, 
      message: '缺少必要参数：userId, title, content' 
    };
  }

  try {
    // 创建通知记录
    const notificationData = {
      user_id: userId,
      type: type || 'system',
      category: category || 'general',
      title: title,
      content: content,
      related_id: relatedId || null,
      related_type: relatedType || null,
      priority: priority,
      action_url: actionUrl || null,
      action_text: actionText || null,
      is_read: false,
      status: 'active',
      create_time: new Date(),
      update_time: new Date()
    };

    console.log('【createNotification】创建通知数据：', notificationData);

    // 插入数据库
    const result = await db.collection('notification-messages').add(notificationData);

    console.log('【createNotification】通知创建结果：', result);

    return {
      success: true,
      message: '通知创建成功',
      data: {
        notificationId: result.id,
        ...notificationData
      }
    };

  } catch (e) {
    console.error('【createNotification】异常:', e);
    return { 
      success: false, 
      message: '通知创建失败：' + e.message 
    };
  }
};
